import React, { Component } from 'react'
import { UdPage, udConfigProvider, UdToolbar, UdTable, IUdTableProps, IUdColumn, columnRenders, http, UdModal, UdModalForm, UdDateRangePicker } from '@/lib'
import { Affix, Button, BackTop, Tabs, message, Modal } from 'antd'
import ButtonGroup from 'antd/lib/button/button-group'
import { PaginationConfig } from 'antd/lib/table'
import apis from '@/apis/SystemSettings'
import QutaValidityCycleModalContent from './QutaValidityCycleModalContent/index'
import dayjs from 'dayjs'

const { TabPane } = Tabs
const { confirm } = Modal

class QuotaValidityPeriod extends Component<IQuotaValidityPeriodProps, IQuotaValidityPeriodState> {
  static resFieldKeys: {
    content: string,
    number: string
    numberOfElements: string
    size: string
    totalElements: string
    totalPages: string
  } = {
      content: 'content',
      number: 'number',
      numberOfElements: 'numberOfElements',
      size: 'size',
      totalElements: 'totalElements',
      totalPages: 'totalPages'
    }
  /** 滚动条容器 */
  protected pageContainer = udConfigProvider.ui.getPageContainer()
  private queryParams = {
    page: 1,
    size: 10,
  }
  private currentBrand
  constructor(props) {
    super(props)
    this.currentBrand = props.tabs[0]?.value
    this.state = {
      querying: false,
      rowKey: 'id',
      pagination: { current: this.queryParams.page, pageSize: this.queryParams.size },
      tableProps: {},
      columns: [
        { title: '品牌公司', dataIndex: 'brandName' },
        { title: '考核年度', dataIndex: 'year' },
        { title: '周期', dataIndex: 'cycleName' },
        { title: '开始时间', dataIndex: 'cycleStartTime', render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '' },
        { title: '结束时间', dataIndex: 'cycleEndTime', render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '' },
        { title: '创建时间', dataIndex: 'createTime' },
        { title: '创建人', dataIndex: 'createName' },
        { title: '最近修改时间', dataIndex: 'updateTime' },
        { title: '最近修改人', dataIndex: 'updateName' },
        {
          title: '操作', dataIndex: 'opreate', fixedWidth: '80px', render: columnRenders.operate([
            { title: '编辑', action: (text, record) => this.updateHandle(record) },
            { title: '删除', action: (text, record) => this.deleteHandle(record) },
          ])
        },
      ],
      dataSource: [],
    }
  }

  componentDidMount() {
    this.query()
  }

  render() {
    const { tabs } = this.props
    return (
      <UdPage className="list-page">
        <Affix className="ud-page-toolbar-affix" offsetTop={40} target={() => this.pageContainer}>
          <UdToolbar other={
            <ButtonGroup>
              <Button type='primary' onClick={this.addHandle}>新增</Button>
            </ButtonGroup>
          }>
          </UdToolbar>
        </Affix>
        <Tabs type='card' onChange={this.tabsChange}>
          {tabs.map(({ value, title }) => {
            return <TabPane tab={title} key={value}></TabPane>
          })}
        </Tabs>
        <UdTable loading={this.state.querying} rowKey={this.state.rowKey}
          pagination={this.state.pagination} {...this.state.tableProps}
          columns={this.state.columns} dataSource={this.state.dataSource}
          onChange={this.handleTableChange}
        />
        {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
      </UdPage>
    )
  }

  public query = () => {
    this.setState({ querying: true })
    const params = { conditions: { brandCode: this.currentBrand }, ...this.queryParams }
    http.post(apis.QuotaValidityCycleList, params).then(res => {
      let pagination = this.state.pagination as PaginationConfig | false
      if (pagination) {
        pagination.current = res.data[QuotaValidityPeriod.resFieldKeys.number]
        pagination.pageSize = res.data[QuotaValidityPeriod.resFieldKeys.size]
        pagination.total = res.data[QuotaValidityPeriod.resFieldKeys.totalElements]
      }
      let data = res.data[QuotaValidityPeriod.resFieldKeys.content]
      this.setState({ dataSource: data, pagination })
    }, err => {
      this.setState({
        dataSource: [],
      })
    }).finally(() => {
      this.setState({ querying: false })
    })
  }

  public handleTableChange = (pagination, filters, sorter, extra) => {
    this.queryParams.page = pagination.current
    this.queryParams.size = pagination.pageSize
    this.query()
  }

  public tabsChange = (key) => {
    this.currentBrand = key
    this.query()
  }

  public addHandle = () => {
    UdModal.open({
      title: '新增配额有效期周期',
      content: <QutaValidityCycleModalContent brandList={this.props.tabs} />,
      onOk: (values) => {
        console.log(values)
        let { brandCode, table, ...formRest } = values
        let brandName = brandCode?.label
        brandCode = brandCode?.key
        const params = table.map(item => {
          const { cycleSort, ...rest } = item
          return { ...rest, ...formRest, brandCode, brandName }
        })
        return http.post(apis.UpdateQuotaValidityCycle, params).then(res => {
          message.success('新增成功')
          this.query()
        })
      }
    })
  }

  public updateHandle = (row) => {
    UdModal.open({
      title: '编辑配额有效期周期',
      content: <UdModalForm items={[
        { label: '品牌公司', id: 'brandName', render: () => <div>{row.brandName}</div> },
        { label: '周期', id: 'cycleName', render: () => <div>{row.cycleName}</div> },
        { label: '考核年度', id: 'year', render: () => {
          const yearStart = row.yearStartTime && dayjs(row.yearStartTime).format('YYYY-MM-DD')
          const yearEnd = row.yearEndTime && dayjs(row.yearEndTime).format('YYYY-MM-DD')
          return <div>{row.year}年（{yearStart}~{yearEnd}）</div>
        } },
        {
          label: '周期起止时间', id: ['cycleStartTime', 'cycleEndTime'], render: () => {
            return <UdDateRangePicker valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']} allowClear={false} />
          }
        },
      ]}
        values={row}
      />,
      onOk: (values) => {
        const params = [{ ...values, id: row.id, yearStartTime: row.yearStartTime, yearEndTime: row.yearEndTime }]
        return http.post(apis.UpdateQuotaValidityCycle, params).then(res => {
          message.success('编辑成功')
          this.query()
        })
      }
    })
  }

  public deleteHandle = (row) => {
    confirm({
      title: '确定要删除此条数据吗？',
      onOk: () => {
        return http.delete(apis.DeleteQuotaValidityCycle, { params: { id: row.id, brandCode: row.brandCode } }).then(res => {
          message.success('删除成功')
          this.query()
        })
      }
    })
  }

}

export default QuotaValidityPeriod

interface IQuotaValidityPeriodProps {
  tabs: any[]
}

interface IQuotaValidityPeriodState {
  querying: boolean
  rowKey: string | ((record: any, index: number) => string)
  pagination: PaginationConfig | false
  tableProps: IUdTableProps<any>
  columns: IUdColumn[]
  dataSource: [],
  currentBrand?: string
}
